import Vue from 'vue';
import iView from 'iview';
import {router} from './router/index';
import {appRouter} from './router/router';
import store from './store';
import App from './app.vue';
import '@/locale';
import 'iview/dist/styles/iview.css';
import VueI18n from 'vue-i18n';
import { VirtualScroller } from 'vue-virtual-scroller';

Vue.use(VueI18n);
Vue.use(iView);
Vue.component('virtual-scroller', VirtualScroller);

import axios from 'axios';
import qs from 'qs';
import Cookies from 'js-cookie';
Vue.prototype.$axios = axios;

// axios 请求发送前处理
axios.interceptors.request.use(function (config) { 
    if(config.method === 'post') {
        config.headers={  
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", 
        } 
        config.data = qs.stringify( {
            ...config.data
        })
    } 
    if(Cookies.get('token')){
        config.headers['token'] = Cookies.get('token');  
    }
    return config;
    }, function (error) {
        return Promise.reject(error);
    })

// http response 服务器响应拦截器，这里拦截401错误，并重新跳入登页重新获取token  
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    })
                    Cookies.remove('token');
                    Cookies.remove('user');
            }
        }
        return Promise.reject(error) 
});


new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    data: {
        currentPageName: ''
    },
    mounted () {
        this.currentPageName = this.$route.name;
        // 显示打开的页面的列表
        this.$store.commit('setOpenedList');
        this.$store.commit('initCachepage');
        // 权限菜单过滤相关
        this.$store.commit('updateMenulist');
        // iview-admin检查更新
        // util.checkUpdate(this);
    },
    created () {
        let tagsList = [];
        appRouter.map((item) => {
            if (item.children.length <= 1) {
                tagsList.push(item.children[0]);
            } else {
                tagsList.push(...item.children);
            }
        });
        this.$store.commit('setTagsList', tagsList);
    }

});
